import HTTP from '@/utils/request'

const getDict = (dictType) => {
    return HTTP.request('GET', {
        url: '/system/dict/data/type/' + dictType,
        isToken: false
    })
}

export const useDict = (...args) => {
    return new Promise((resolve, reject) => {
        const dictStorage = wx.getStorageSync('DICT_DATA');
        const dictData = JSON.parse(dictStorage || '{}');
        const dictValues = {}
        args.forEach((dictType, index) => {
            const dicts = dictData[dictType]
            if (dicts) {
                dictValues[dictType] = dicts
            } else {
                getDict(dictType).then((res) => {
                    dictValues[dictType] = res.data.map(p => ({
                        label: p.dictLabel,
                        value: p.dictValue,
                        elTagType: p.listClass,
                        elTagClass: p.cssClass
                    }))
                    dictData[dictType] = dictValues[dictType]
                    wx.setStorage('DICT_DATA', JSON.stringify(dictData))
                })
            }
        })
        let ins = 0;
        const interval = setInterval(() => {
            let isCs = true
            for (let index = 0; index < args.length; index++) {
                if (!dictValues.hasOwnProperty(args[index])) {
                    isCs = false
                }
            }
            if (isCs) {
                resolve(dictValues);
                clearInterval(interval)
            } else if (ins > 25) {
                reject()
                clearInterval(interval)
            }
            ins++
        }, 200)
    })
}